package com.ezlcp.user.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ezlcp.commons.base.db.BaseDao;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.IUser;
import com.ezlcp.commons.constant.Constants;
import com.ezlcp.commons.service.impl.SuperServiceImpl;
import com.ezlcp.commons.tool.IdGenerator;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.commons.utils.TokenUtil;
import com.ezlcp.user.entity.Settings;
import com.ezlcp.user.mapper.SettingsMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * [租户配置]业务服务类
 */
@Service
public class SettingsServiceImpl extends SuperServiceImpl<SettingsMapper, Settings> implements BaseService<Settings> {
    @Resource
    private SettingsMapper settingsMapper;
    @Resource
    private LogService logService;
    /***
     * @description: 修改系统预设值
     * @param Settings 修改系统预设值
     * @return java.lang.Boolean
     * @author ou zhen
     * @date 2022/5/11 17:17
     */
    public Boolean updateSettings(Settings Settings) {
        return settingsMapper.updateById(Settings)>0;
    }

    /***
    * @description  获取当前企业的配置信息
    * @return com.ezlcp.user.entity.Settings
    * @author Elwin ZHANG
    * @date 2023/4/10 16:57
    */
    public Settings getCurSetting(){
        String tenantId=ContextUtil.getCurrentTenantId();
        QueryWrapper<Settings> wrapper = new QueryWrapper<>();
        if(StringUtils.isEmpty(tenantId)){
            wrapper.and(query -> query.eq(Constants.COL_TENANT_ID, "").or().isNull(Constants.COL_TENANT_ID));
        }else {
            wrapper.eq(Constants.COL_TENANT_ID, tenantId);
        }
        return this.settingsMapper.selectOne(wrapper);
    }

    /**
     * @param tenantId 公司ID
     * @return com.ezlcp.user.entity.Settings 系统设置项
     * @description: 根據公司tenant_id查詢
     * @author ou zhen
     * @date 2022/5/9 10:12
     */
    public Settings selectByTenantId(String tenantId) {
        QueryWrapper<Settings> settingsQueryWrapper = new QueryWrapper<>();
        settingsQueryWrapper.eq(Constants.COL_TENANT_ID, tenantId);
        return settingsMapper.selectOne(settingsQueryWrapper);
    }

    /**
     * @param tenantId 公司ID
     * @return com.ezlcp.user.entity.Settings
     * @description: 获取公司系统预设值，如果没有记录，则从系统默认配置中复制一份
     * @author ou zhen
     * @date 2022/5/20 18:18
     */
    @Transactional(rollbackFor = Exception.class)
    public Settings getByTenant(String tenantId) {
        if (StringUtils.isEmpty(tenantId)) {
            return getDefaultSet();
        }
        QueryWrapper<Settings> wrapper = new QueryWrapper<>();
        wrapper.eq(Constants.COL_TENANT_ID, tenantId);
        Settings settings = settingsMapper.selectOne(wrapper);
        //如果取到值，则直接返回
        if (settings != null) {
            return settings;
        }
        //获取默认值
        settings = getDefaultSet();
        if (settings == null) {
            throw new RuntimeException("數據庫中沒有初始化");
        }
        //复制系统默认配置
        settings.setId(IdGenerator.getIdStr());
        settings.setTenantId(tenantId);
        settings.setSeq(1);
        insert(settings);
        logService.saveSystemLog("系统预设值赋值", "/registerCompany", settings.getPkId(), JSON.toJSONString(settings));
        return settings;
    }

    /**
     * @return com.ezlcp.user.entity.Settings
     * @description: 获取默认的系統預設值
     * @author ou zhen
     * @date 2022/5/20 18:23
     */
    public Settings getDefaultSet() {
        QueryWrapper<Settings> wrapper = new QueryWrapper<>();
        wrapper.and(query -> query.eq(Constants.COL_TENANT_ID, "").or().isNull(Constants.COL_TENANT_ID));
        return settingsMapper.selectOne(wrapper);
    }


    /***
     * @description 获取配置中的登录失败最大次数
     * @param settings 公司配置信息
     * @return int 如果值小于等于0，则忽略
     * @author Elwin ZHANG
     * @date 2023/1/29 11:40
     */
    public int getMaxLoginFailTimes(Settings settings) {
        if (settings == null || settings.getLoginFailTimes() == null) {
            return 5;
        }
        return settings.getLoginFailTimes();
    }

    /***
     * @description 获取配置中的登录锁定时间（分钟）
     * @param settings 公司配置信息
     * @return int 如果值小于等于0，则忽略
     * @author Elwin ZHANG
     * @date 2023/1/29 11:40
     */
    public int getLockMinutes(Settings settings) {
        if (settings == null || settings.getLockMinutes() == null) {
            return 60;
        }
        return settings.getLockMinutes();
    }

    /***
     * @description 获取配置中的IP策略
     * @param settings 公司配置信息
     * @return int 未配置则返回0
     * @author Elwin ZHANG
     * @date 2023/1/29 11:40
     */
    public int getIpStrategy(Settings settings){
        if (settings == null || settings.getIpStrategy() == null) {
            return 0;
        }
        return settings.getIpStrategy();
    }

    /***
    * @description  获取配置中的 空闲几分钟自动登出
    * @param settings 公司配置信息
    * @return int 未配置则返回60
    * @author Elwin ZHANG
    * @date 2023/2/7 9:59
    */
    public int getIdleMinutes(Settings settings) {
        if (settings == null || settings.getIdleMinutes() == null) {
            return TokenUtil.LOGIN_IDLE_MINUTES;
        }
        return settings.getIdleMinutes();
    }

    @Override
    public BaseDao<Settings> getRepository() {
        return settingsMapper;
    }
}